<template>
  <div class="category-manage">
    <div class="page-header">
      <h2>分类管理</h2>
      <p>管理衣服分类，支持层级分类</p>
    </div>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>分类列表</span>
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>
            添加分类
          </el-button>
        </div>
      </template>

      <!-- 分类表格 -->
      <el-table
        :data="categoryList"
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
      >
        <el-table-column prop="name" label="分类名称" width="200">
          <template #default="{ row }">
            <span :style="{ paddingLeft: (row.level - 1) * 20 + 'px' }">
              {{ row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="name_en" label="英文名称" width="150" />
        <el-table-column prop="level" label="层级" width="80" />
        <el-table-column prop="sort_order" label="排序" width="80" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editCategory(row)">编辑</el-button>
            <el-button size="small" @click="addSubCategory(row)">添加子分类</el-button>
            <el-button size="small" type="danger" @click="deleteCategory(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑分类' : '添加分类'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>

        <el-form-item label="英文名称" prop="name_en">
          <el-input v-model="categoryForm.name_en" placeholder="请输入英文名称" />
        </el-form-item>

        <el-form-item label="父分类" prop="parent_id">
          <el-select v-model="categoryForm.parent_id" placeholder="选择父分类" clearable>
            <el-option label="无（顶级分类）" :value="null" />
            <el-option
              v-for="category in parentCategories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="categoryForm.sort_order" :min="1" :max="999" />
        </el-form-item>

        <el-form-item label="图标" prop="icon">
          <el-input v-model="categoryForm.icon" placeholder="图标类名（可选）" />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="categoryForm.description"
            type="textarea"
            :rows="3"
            placeholder="分类描述（可选）"
          />
        </el-form-item>

        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="categoryForm.is_active" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="saveCategory">
          {{ saving ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { categoryAPI } from '@/api'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const categoryList = ref([])
const formRef = ref()

// 表单数据
const categoryForm = reactive({
  id: null,
  name: '',
  name_en: '',
  parent_id: null,
  level: 1,
  sort_order: 1,
  icon: '',
  description: '',
  is_active: true
})

// 表单验证规则
const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '分类名称长度在2-50个字符', trigger: 'blur' }
  ],
  name_en: [
    { required: true, message: '请输入英文名称', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '英文名称只能包含字母、数字、下划线和连字符', trigger: 'blur' }
  ],
  sort_order: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 可选的父分类（排除当前编辑的分类及其子分类）
const parentCategories = computed(() => {
  if (!isEdit.value) {
    return categoryList.value.filter(cat => cat.level === 1)
  }
  // 编辑时需要排除自己和子分类
  return categoryList.value.filter(cat => 
    cat.level === 1 && 
    cat.id !== categoryForm.id
  )
})

// 加载分类列表
const loadCategories = async () => {
  try {
    loading.value = true
    const response = await categoryAPI.getList()
    
    if (response.code === 200) {
      categoryList.value = buildCategoryTree(response.data || [])
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 构建分类树
const buildCategoryTree = (categories) => {
  const tree = []
  const map = {}
  
  // 先创建映射
  categories.forEach(cat => {
    map[cat.id] = { ...cat, children: [] }
  })
  
  // 构建树结构
  categories.forEach(cat => {
    if (cat.parent_id) {
      if (map[cat.parent_id]) {
        map[cat.parent_id].children.push(map[cat.id])
      }
    } else {
      tree.push(map[cat.id])
    }
  })
  
  return tree
}

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑分类
const editCategory = (category) => {
  isEdit.value = true
  Object.assign(categoryForm, {
    id: category.id,
    name: category.name,
    name_en: category.name_en,
    parent_id: category.parent_id,
    level: category.level,
    sort_order: category.sort_order,
    icon: category.icon || '',
    description: category.description || '',
    is_active: category.is_active
  })
  dialogVisible.value = true
}

// 添加子分类
const addSubCategory = (parentCategory) => {
  isEdit.value = false
  resetForm()
  categoryForm.parent_id = parentCategory.id
  categoryForm.level = parentCategory.level + 1
  dialogVisible.value = true
}

// 保存分类
const saveCategory = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    saving.value = true
    
    let response
    if (isEdit.value) {
      response = await categoryAPI.update(categoryForm.id, categoryForm)
    } else {
      response = await categoryAPI.create(categoryForm)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '分类更新成功' : '分类创建成功')
      dialogVisible.value = false
      loadCategories()
    } else {
      throw new Error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('保存分类失败:', error)
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    saving.value = false
  }
}

// 删除分类
const deleteCategory = (category) => {
  ElMessageBox.confirm(
    `确定要删除分类"${category.name}"吗？删除后不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await categoryAPI.delete(category.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadCategories()
      } else {
        throw new Error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除分类失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(categoryForm, {
    id: null,
    name: '',
    name_en: '',
    parent_id: null,
    level: 1,
    sort_order: 1,
    icon: '',
    description: '',
    is_active: true
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 页面初始化
onMounted(() => {
  loadCategories()
})
</script>

<style scoped>
.category-manage {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-table {
  margin-top: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .category-manage {
    padding: 16px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
}
</style>
